﻿#include "SVTemplateController.h"

SVTemplateController::SVTemplateController(QWidget *widget, QObject *parent)
    : QObject(parent)
    , mTemplateView(new SVTemplateView(widget))
    , mCalculateModel(nullptr)
    , mTemplateListModel(new QStandardItemModel(this))
{
    mTemplateView->setTemplateListModel(mTemplateListModel);
    connect(mTemplateView,
            &SVTemplateView::addTemplateRequested,
            this,
            &SVTemplateController::onAddTemplateRequested);
    connect(mTemplateView,
            &SVTemplateView::removeTemplateRequested,
            this,
            &SVTemplateController::onRemoveTemplateRequested);
}

void SVTemplateController::loadCalculateModel(SVCalculateModel *model)
{
    mCalculateModel = model;
}

QWidget *SVTemplateController::getView() const
{
    return mTemplateView;
}

void SVTemplateController::onAddTemplateRequested()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(
        nullptr, tr("Open Template Image"), "", tr("Image Files (*.png *.jpg *.bmp)"));
    for (auto fileName : fileNames) {
        PCBTemplateFeatures features = mCalculateModel->extractFeatures(QImage(fileName));
        TEMPLATEMODEL->addTemplateImage(features);
        QStandardItem *item = new QStandardItem(QIcon(fileName), "");
        mTemplateListModel->appendRow(item);
    }
}

void SVTemplateController::onRemoveTemplateRequested(const QList<int> &indexs)
{
    for (auto index : indexs) {
        TEMPLATEMODEL->removeTemplateImage(index);
        mTemplateListModel->removeRow(index);
    }
}
